package net.shenru.encogs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import net.shenru.os.utlis.SrLog;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

public class EncogBus extends Encog {

	private static final String TAG = EncogBus.class.getSimpleName();

	@Override
	public void onEncog() {
		SrLog.i(TAG, "我开始爬了");
		HttpClient client = new DefaultHttpClient();
		// ClientConnectionManager connectionManager =
		// client.getConnectionManager();
		// connectionManager.closeIdleConnections(40, TimeUnit.SECONDS);

		HttpGet getRequest = new HttpGet("http://beijing.8684.cn/line1");
		BasicHeader charsetHeader = new BasicHeader("Accept-Charset", "UTF-8");
		getRequest.setHeader(charsetHeader);
//		HttpGet getRequest = new HttpGet("http://bus.bj.bendibao.com/linelist/1.htm");
//		 HttpGet getRequest = new HttpGet("http://www.baidu.com");
		try {
			HttpResponse responseResult = client.execute(getRequest);
			SrLog.i(TAG, responseResult.getStatusLine() + "");

			HttpEntity entity = responseResult.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				try {

					BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
					// do something useful with the response
					SrLog.i(TAG, new String(reader.readLine().getBytes(),"UTF-8"));
				} catch (IOException ex) {

					// In case of an IOException the connection will be released
					// back to the connection manager automatically
					throw ex;

				} catch (RuntimeException ex) {

					// In case of an unexpected exception you may want to abort
					// the HTTP request in order to shut down the underlying
					// connection and release it back to the connection manager.
					getRequest.abort();
					throw ex;

				} finally {

					// Closing the input stream will trigger connection release
					instream.close();

				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		client.getConnectionManager().shutdown();
	}

}
